/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.data.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import edu.cmu.lti.sepia.infra.topic.model.Answer;
import edu.cmu.lti.sepia.util.ServletUtil;

/**
 * 
 * Manages Answer object in a DB.
 * 
 * @see Answer
 * @author Hideki Shima
 *
 */
public class AnswerDAO {
	
	public static void addAnswer( SQL sql, String table, Answer answer ) throws SQLException {		
		String query = Query.generate( Query.INSERT_ANSWER, table );
		
		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		ps.setInt(1, answer.getTopicId());
		ps.setString(2, answer.getDocumentId());
		ps.setInt(3, answer.getBegin());
    ps.setInt(4, answer.getEnd());
		ps.setString(5, answer.getAnswerBearingText());
		ps.setString(6, answer.getOriginalAnswerBearingText());
		ps.setString(7, answer.getLabel());
		sql.executeInSilence(ps);
		ps.close();
	}

	public static void addAnswers( SQL sql, String table, List<Answer> answers ) throws SQLException {		
    if ( answers!=null ) {
      for ( Answer answer : answers ) {
        AnswerDAO.addAnswer( sql, table, answer );
      }
    }
	}
	
	public static void updateAnswerBearingText( SQL sql, String table, int answerId, String answerBearingText ) throws SQLException {
	  String query = Query.generate( Query.UPDATE_ANSWER_TEXT, table );
	  PreparedStatement ps = sql.getConnection().prepareStatement(query);
	  ps.setString(1, answerBearingText);
    ps.setInt(2, answerId);
	  sql.execute(ps);
	  ps.close();
	}

	public static void updateLabel( SQL sql, String table, int answerId, String label ) throws SQLException {
	  String query = Query.generate( Query.UPDATE_ANSWER_LABEL, table );
	  PreparedStatement ps = sql.getConnection().prepareStatement(query);
	  ps.setString(1, label);
	  ps.setInt(2, answerId);
	  sql.execute(ps);
	  ps.close();
	}

	public static void deleteAnswer( SQL sql, String table, int answerId ) throws SQLException {
		String query = Query.generate( Query.DELETE_ANSWER, table );
		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		ps.setInt(1, answerId);
		sql.execute(ps);
		ps.close();
	}
	
	public static void deleteAnswersByTopicId( SQL sql, String table, int topicId ) throws SQLException {
		String query = Query.generate( Query.DELETE_BYTOPIC, table );
		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		ps.setInt(1, topicId);
		sql.execute(ps);
		ps.close();
	}
	
	public static List<Answer> findByTopicId( SQL sql, String table, int topicId ) throws SQLException {
		String query = Query.generate( Query.FIND_ANSWER, table );
		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		ResultSet rs = null;
		
		List<Answer> answers = new ArrayList<Answer>();
		ps.setInt(1, topicId);
		rs = sql.executeSelect(ps);
	
		while ( rs.next() ) {
			answers.add( rsToObject(rs) );
		}

		rs.close();
		ps.close();
		return answers;
	}
	
	private static Answer rsToObject( ResultSet rs ) throws SQLException {
		Answer answer = new Answer( rs.getInt(1), rs.getInt(2), 
				rs.getString(3), rs.getInt(4), rs.getInt(5), 
				rs.getString(6), rs.getString(7), rs.getString(8) );
		return answer;
	}

  public static JSONArray convertAnswers( List<Answer> answers ) throws JSONException {
    JSONArray jsonArray = new JSONArray();
    if ( answers!=null ) {
      for ( Answer a : answers ) {
        JSONObject j = new JSONObject();
        j.put("answerId", a.getAnswerId());
        j.put("answerBearingText", a.getAnswerBearingText());
        j.put("originalAnswerBearingText", a.getOriginalAnswerBearingText());
        j.put("label", a.getLabel());
        j.put("documentId", a.getDocumentId());
        j.put("begin", a.getBegin());
        j.put("end", a.getEnd());
        jsonArray.put(j);
      }
    }
    return jsonArray;
  }
  
  public static Answer parseRequest( HttpServletRequest request ) {
    if ( request.getParameter("answerBearingText")==null 
        && request.getParameter("answerId")==null ) return null;
    
    ServletUtil s = new ServletUtil( request );

    return new Answer( 
        s.readInt("answerId", 0),
        s.readInt("topicId", 0),
        s.readString("documentId", ""),
        s.readInt("begin", 0),
        s.readInt("end", 0),
        s.readString("answerBearingText", ""),
        s.readString("originalAnswerBearingText", ""),
        s.readString("label", "")
    );
  }
}
